package lion.blog;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lion.blog.util.BlogUtil;
import lion.dev.io.FileUtil;
import lion.dev.web.WebUtil;
import lion.framework.core.web.anno.ExceptionHandler;
import lion.framework.core.web.exception.IExceptionHandler;
import lion.framework.core.web.exception.WebException;

/**
 * 
 * 博客路径下的异常处理，将错误引导至主题页面下的相关错误提示页面
 * 
 * @author lion
 * @email hl_0074@sina.com
 * @date 2015年8月27日
 */
@ExceptionHandler("/#{blog}/.*")
public class BlogExceptionHandler implements IExceptionHandler {

	@Override
	public void handler(HttpServletRequest request, HttpServletResponse response, WebException exception) {

		request.setAttribute("exception", exception);

		int status = exception.getStatus();
		String file = "error.jsp";
		if (status == 404 && BlogUtil.hasFile("404.jsp")) {
			file = "404.jsp";
		}
		if (BlogUtil.hasFile(file)) {
			file = BlogUtil.getPath(file);
			forward(request, response, exception, file);
		} else {
			writeMessage(request, response, exception);
		}
	}

	private void writeMessage(HttpServletRequest request, HttpServletResponse response, WebException exception) {

		if (exception.getMessage() != null) {
			try {
				response.getWriter().write(exception.getStatus() + ":" + exception.getMessage());
			} catch (IOException e) {
			}
		}
	}

	private void forward(HttpServletRequest request, HttpServletResponse response, WebException exception, String file) {

		WebUtil.exposeForwardAttribute(request);
		WebUtil.exposeErrorAttribute(request, exception);
		try {
			request.getRequestDispatcher(FileUtil.toUnixPath(file)).forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
